package com.vincce.sport.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.bbs.client.Client;
import com.vincce.sport.core.bbs.util.XMLHelper;
import com.vincce.sport.core.entity.DateViewSession;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.Constant;
import com.vincce.sport.core.utils.ConvertUtil;
import com.vincce.sport.core.utils.RedisUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.Activity;
import com.vincce.sport.entity.Advert;
import com.vincce.sport.entity.DateView;
import com.vincce.sport.entity.DzForumPost;
import com.vincce.sport.entity.ImgModel;
import com.vincce.sport.entity.ImgStorage;
import com.vincce.sport.entity.InvitationCode;
import com.vincce.sport.entity.News;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.Team;
import com.vincce.sport.entity.User;
import com.vincce.sport.mapper.ActivityMapper;
import com.vincce.sport.mapper.AdvertMapper;
import com.vincce.sport.mapper.BbsPostMapper;
import com.vincce.sport.mapper.DateViewMapper;
import com.vincce.sport.mapper.ImgModelMapper;
import com.vincce.sport.mapper.ImgStorageMapper;
import com.vincce.sport.mapper.InvitationCodeMapper;
import com.vincce.sport.mapper.NewsMapper;
import com.vincce.sport.mapper.TeamMapper;
import com.vincce.sport.mapper.UserMapper;

@Controller
@RequestMapping("/")
public class IndexController {
	@Resource
	private AdvertMapper advertMapper;
	@Resource
	private NewsMapper newsmapper;
	@Resource
	private ImgStorageMapper imgStorageMapper;
	@Resource
	private DateViewMapper dateViewMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private TeamMapper teamMapper;
	@Resource
	private ImgModelMapper imgModelMapper;
	@Resource
	private ActivityMapper activityMapper;
	@Resource
	private BbsPostMapper bbsPostMapper;
	@Resource
	private InvitationCodeMapper invitationCodeMapper;
	
	@RequestMapping("/index")
    public String sportIndex(Model model, HttpServletRequest request, String msg) throws ParseException{
		if(msg == null){
			msg = "";
		}
		model.addAttribute("msg", msg);
		Page<Advert> footerAdvertPage=new Page<Advert>();
		Page<News> hotNewsPage=new Page<News>();
		Page<News> remarkNewsPage=new Page<News>();
		Page<Advert> page3=new Page<Advert>();
        Page<Advert> page5=new Page<Advert>();
		Page<DzForumPost> page4=new Page<DzForumPost>();
		Map<String, Object> filter = new HashMap<String, Object>();
		//首页底部广告位
	    filter=new HashMap<String, Object>();	
	    filter.put("name", "首页底部");
	    filter.put("status", 1);
	    footerAdvertPage.setLimit(4);
	    footerAdvertPage.setFilter(filter);
	    footerAdvertPage.setResult(replace(advertMapper.queryAdvertList(footerAdvertPage)));
	    model.addAttribute("footerAdvertPage",footerAdvertPage);
	    //热点新闻	 
	    filter=new HashMap<String, Object>();	
		filter.put("status", 1);
		hotNewsPage.setFilter(filter);
		hotNewsPage.setLimit(10);
		hotNewsPage.setResult(replaceNews(newsmapper.queryNewsList(hotNewsPage)));
        model.addAttribute("hotNewsPage",hotNewsPage); 
        //专家点评
        filter=new HashMap<String, Object>();	
		filter.put("status", 1);
		filter.put("type", 1);
		remarkNewsPage.setFilter(filter);
		remarkNewsPage.setLimit(3);
		remarkNewsPage.setResult(replaceNews(newsmapper.queryNewsList(remarkNewsPage)));
        model.addAttribute("remarkNewsPage",remarkNewsPage); 
        
        //首页精彩图片广告位
	    filter=new HashMap<String, Object>();	
	    filter.put("name", "首页精彩图片");
	    filter.put("status", 1);
	    page3.setLimit(1);
	    page3.setFilter(filter);
	    page3.setResult(advertMapper.queryAdvertList(page3));
        //精彩图库	
        Map<String, Object> filter6 = new HashMap<String, Object>();
		Page<ImgModel> page6=new Page<ImgModel>();
		filter6.put("status", 1);
        page6.setFilter(filter6);
        page6.setLimit(1);
        page6.setResult(imgModelMapper.queryImgModelList(page6));
        if(page6!=null && page6.getResult().size()>0){
//        	Long modelId=page6.getResult().get(0).getId();
//        	ImgStorage imgStorage = new ImgStorage();			
//			imgStorage.setModelId(modelId);
//			List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
//			if(imgStorageList!=null && imgStorageList.size()>0){
				String imgPath=page3.getResult().get(0).getAdvertImg();
				page6.getResult().get(0).setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+imgPath, "ori"));
//			}
        }
        model.addAttribute("imgStorageList", page6);
        
//        //获取活动
//        Activity activity = new Activity();
//		activity.setStatus("1");
//		List<Activity> activitylist = activityMapper.findActivityByOne(activity);
//		if(activitylist!=null && activitylist.size()>0){
//			activity = activitylist.get(0);
//			activity.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activity.getImgPath(), "ori"));
//		}
        filter=new HashMap<String, Object>();
        filter.put("name", "首页话题互动");
        filter.put("status", 1);
        page5.setLimit(1);
        page5.setFilter(filter);
        page5.setResult(replace(advertMapper.queryAdvertList(page5)));
		model.addAttribute("activity", page5);
		//首页精华帖		    
		page4.setLimit(6);	    
		page4.setResult(bbsPostMapper.queryPostPage(page4));
	    model.addAttribute("dzForumPostList",page4);
		//取redis	
		DateViewSession dateViewSession=new DateViewSession();
        dateViewSession = RedisUtil.cacheGet(RedisUtil.DB_SPORT_DATEVIEW, "dateViewKey", DateViewSession.class);
		List<DateView> playerDateByTotalScoreList=new ArrayList<DateView>();
		List<DateView> playerDateByBackboardList=new ArrayList<DateView>();
		List<DateView> playerDateByAssistsAstsList=new ArrayList<DateView>();
		List<DateView> teamDateByBackboardList=new ArrayList<DateView>();
		List<DateView> teamDateByTotalScoreList=new ArrayList<DateView>();
		List<DateView> teamDateByHitList=new ArrayList<DateView>();
		if(dateViewSession!=null && dateViewSession.getDateViewList().size()>0){
			for(DateView dateView:dateViewSession.getDateViewList()){
				if(dateView.getType()==1){
					//场均得分
					playerDateByTotalScoreList.add(dateView);
				}
				if(dateView.getType()==2){
					//场均篮板排名
					playerDateByBackboardList.add(dateView);
				}
				if(dateView.getType()==3){
					//场均助攻排名
					playerDateByAssistsAstsList.add(dateView);
				}
				if(dateView.getType()==4){
					//命中率排名-球队
					teamDateByHitList.add(dateView);
				}
				if(dateView.getType()==5){
					//场均篮板排名-球队
					teamDateByBackboardList.add(dateView);
				}
				if(dateView.getType()==6){
					//场均得分排名-球队
					teamDateByTotalScoreList.add(dateView);
				}
			}
		}
		//场均得分	
		model.addAttribute("d1List", playerDateByTotalScoreList);		
		//场均篮板排名		
		model.addAttribute("d2List", playerDateByBackboardList);	
		//场均助攻排名		
		model.addAttribute("d3List", playerDateByAssistsAstsList);	
		//命中率排名-球队	
		model.addAttribute("d4List", teamDateByHitList);			
		//场均篮板排名-球队		
		model.addAttribute("d5List", teamDateByBackboardList);			
		//场均得分排名-球队		
		model.addAttribute("d6List", teamDateByTotalScoreList);
		if(dateViewSession!=null){
			if(dateViewSession.getUpdateTime()!=null){
				String dd=dateViewSession.getUpdateTime();
				model.addAttribute("dd", dd.substring(0,4)+"年"+dd.substring(5,7)+"月"+dd.substring(8,10)+"日");
			}else{
				model.addAttribute("dd", null);
			}
		}else{
			model.addAttribute("dd", null);
		}		
        return "foreground/index";
    }
    //----------------------------------------前台----------------------------------------------//
    
    /**
     * 登陆
     * @param model
     * @param user
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public String userLogin(Model model, User user, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	Long count = 0l;
    	String msg="";
    	//密码md5加密
    	try {
    		user.setPassword(ConvertUtil.encryptMD5(user.getPassword()));
		} catch (Exception e) {
			e.printStackTrace();
		} 
    	User userInfo=userMapper.findUserByNameAndPassword(user);
    	if(userInfo!=null){
    		System.out.println("*********************************************USER = "+userInfo.toString());
    		request.getSession().setAttribute(Constant.T_USER, userInfo);
			msg="登录成功"; 
			count = 1l; 
			//BBS联合登陆
//			msg = bbsLogin(user.getUserName(),user.getPassword(),response);
//			try {
//				response.setContentType( "text/html;charset=utf-8" ) ;  //设置响应页面字符编码
//				PrintWriter out = response.getWriter();
//		        out.println("登录成功"+msg);
//		        out.close() ;
//			} catch (IOException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
    	}else{
			msg="用户名或密码错误"; 
			count = 0l;
    	}        
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("msg", msg);
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }
    /**
     * 注册
     * @param model
     * @param user
     * @param request
     * @param invitationCode
     * @return
     * @throws IOException
     */
    @RequestMapping("/userRegister")
    @ResponseBody
    public String userRegister(Model model, User user, HttpServletRequest request,String invitationCode) throws IOException{
    	String email=user.getEmail();
    	Long count = 0l;
    	String msg="";
    	String pas=user.getPassword();
    	if(checkUserNameList(user.getUserName(),null)){
    		//密码md5加密
            if(user.getPassword()!=null && !"".equals(user.getPassword())){
            	try {
            		user.setPassword(ConvertUtil.encryptMD5(user.getPassword()));
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
            }                
            if(CheckUtil.isEmpty(user.getId())){
                if(invitationCode!=null && !"".equals(invitationCode)){
                	InvitationCode iCode= invitationCodeMapper.selectByInvitationCode(invitationCode);
                    if(iCode!=null){
                    	if(iCode.getStatus().equals("是")){
                    		count = 0l;
                            msg="邀请码已被使用";
                    	}else{
                    		//创建 人和创建时间
                            user.setCreateUser(null);
                            user.setCreateTime(new Date());
                            user.setUpdateTime(new Date());
                            user.setStatus(1);
                            count = userMapper.insertUser(user);                                              
                            User userInfo=userMapper.findUserByNameAndPassword(user);                    	
                        	try {
                        		//BBS注册
                        		BbsController.testRegister(user.getUserName(),pas,email);
                                msg="注册成功";
                                //更新邀请码为已使用
                                InvitationCode inCode=new InvitationCode();
                                inCode.setCode(invitationCode);
                                inCode.setStatus("是");
                                invitationCodeMapper.updateInvitationCode(inCode);
                			} catch (Exception e) {
                				e.printStackTrace();
                				msg="注册失败";
                				count = 0l;            				
                				userMapper.deleteById(userInfo.getId());
                				userInfo=null;
                			}
                        	if(userInfo!=null){
                        		//更新session
                        		request.getSession().setAttribute(Constant.T_USER, userInfo);
                        	}
                    	}                                               
                    }else{
                        count = 0l;
                        msg="邀请码不存在,或已失效";
                    }
                }

            }
    	}else{
    		 msg="注册名已存在"; 
    		 count = 0l;
    	}        
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("msg", msg);
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }
    /**
     * 退出
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/exit")
    public String exit(Model model, HttpServletRequest request,HttpServletResponse response) throws Exception{
    	request.getSession().removeAttribute(Constant.T_USER); 
//    	bbsLogout(response);
    	BbsController.testLogout(response);
    	return null;
    }
    public Boolean checkUserNameList(String userName,Long id){
    	User user=new User();
        if(userName != null && !userName.equals("")){
            user.setUserName(userName);
        }
        if(id!= null && !id.equals("")){
            user.setId(id);
        }
        
        Integer fg = 0;
        List<User> userList = userMapper.findUserByOne(user);
        if(userList!=null && userList.size()>0){
        	fg = 1;
        }
        return fg==0;
    }
	/**
	 * 图片路径替换
	 * @param advertList
	 * @return
	 */
	public List<Advert> replace(List<Advert> advertList){
		if(advertList!=null && advertList.size()>0){
			for(Advert adv:advertList){
				adv.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+adv.getAdvertImg(), "ori"));
			}
		}
		return advertList;
	}
	/**
	 * 图片路径替换
	 * @param newsList
	 * @return
	 * @throws ParseException 
	 */
	public List<News> replaceNews(List<News> newsList) throws ParseException{
		if(newsList!=null && newsList.size()>0){
			for(News news:newsList){
				news.setNewsImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+news.getNewsImg(), "ori"));	
				news.setSpecialistImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+news.getSpecialistImg(), "ori"));
			}
		}
		return newsList;
	}
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<ImgStorage> replaceImgStorage(List<ImgStorage> imgStorageList){
		if(imgStorageList!=null && imgStorageList.size()>0){
			for(ImgStorage isl:imgStorageList){
				isl.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+isl.getImgPath(), "ori"));
			}
		}
		return imgStorageList;
	}
	
//	public void bbsLogin(String userName,String password,HttpServletResponse response){
//		Client e = new Client();
//		String result = e.uc_user_login(userName, password);
//		LinkedList<String> rs = XMLHelper.uc_unserialize(result);
//		if(rs.size()>0){
//			int $uid = Integer.parseInt(rs.get(0));
//			String $username = rs.get(1);
//			String $password = rs.get(2);
//			String $email = rs.get(3);
//			if($uid > 0) {
//				System.out.println("登录成功");
//				System.out.println($username);
//				System.out.println($password);
//				System.out.println($email);
//				
//				String $ucsynlogin = e.uc_user_synlogin($uid);
//				System.out.println("登录成功"+$ucsynlogin);
//
//				//本地登陆代码
//				//TODO ... ....
//		        
//			} else if($uid == -1) {
//				System.out.println("用户不存在,或者被删除");
//			} else if($uid == -2) {
//				System.out.println("密码错");
//			} else {
//				System.out.println("未定义");
//			}
//		}else{
//			System.out.println("Login failed");
//			System.out.println(result);
//		}
//	}
//	
//	public void bbsLogout(HttpServletResponse response){
//		
//		Client uc = new Client();
//
//		//setcookie('Example_auth', '', -86400);
////		生成同步退出的代码
//		String $ucsynlogout = uc.uc_user_synlogout();
//		System.out.println("退出成功"+$ucsynlogout);
//		
//		try {
//			PrintWriter out = response.getWriter();
//			out.println("<div>退出成功！</div>"+$ucsynlogout+"<script>window.location.href='/index.html'</script>");
//		    out.close() ;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//	}
//	
//	public void bbsRegister(String userName,String password,String email){
//		
//		Client uc = new Client();
//
//		//setcookie('Example_auth', '', -86400);
////		生成同步退出的代码
//		String $returns = uc.uc_user_register(userName, password, email);
//		int $uid = Integer.parseInt($returns);
//		if($uid <= 0) {
//			if($uid == -1) {
//				System.out.print("用户名不合法");
//			} else if($uid == -2) {
//				System.out.print("包含要允许注册的词语");
//			} else if($uid == -3) {
//				System.out.print("用户名已经存在");
//			} else if($uid == -4) {
//				System.out.print("Email 格式有误");
//			} else if($uid == -5) {
//				System.out.print("Email 不允许注册");
//			} else if($uid == -6) {
//				System.out.print("该 Email 已经被注册");
//			} else {
//				System.out.print("未定义");
//			}
//		} else {
//			System.out.println("OK:"+$returns);
//		}
//		
//
//	}
}
